<template>
  <el-card>
    <template #header>管理员信息</template>
    <!-- 个人中心页面布局 -->
    <el-row>
      <el-col>管理员ID:</el-col><el-col>{{ users.id }}</el-col>
    </el-row>
    <el-row>
      <el-col>账号:</el-col><el-col>{{ users.account }}</el-col>
    </el-row>
    <el-row>
      <el-col>用户组:</el-col><el-col>{{ users.userGroup }}</el-col>
    </el-row>
    <el-row>
      <el-col>创建时间:</el-col><el-col>{{ users.ctime | format }}</el-col>
    </el-row>
    <el-row>
      <el-col>管理员头像:</el-col>
      <el-col>
        <!-- 上传头像组件 -->
        <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:5000/users/avatar_upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-col>
    </el-row>
    <el-row>
      <el-col></el-col>
      <el-col>
        <el-button type="primary" size="mini" @click="saveImg"
          >保存头像</el-button
        >
      </el-col>
    </el-row>
  </el-card>
</template>

<script>
import local from '@/utils/local.js'
import { editUserImg } from '@/api/users.js'

export default {
  data() {
    return {
      imageUrl: '',
      users: {},
      str: ''
    }
  },
  created() {
    this.users = JSON.parse(local.get('users'))
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(res)
      this.str = res.imgUrl
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const arr = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!arr.includes(file.type)) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return arr.includes(file.type) && isLt2M
    },
    // 上传头像
    async saveImg() {
      const { code } = await editUserImg({
        imgUrl: this.str
      })
      // console.log(data)
      if (code === 0) {
        location.reload()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  padding: 15px 5px;
  border-bottom: 1px solid #e4e4e4;
  display: flex;
  justify-content: flex-start;

  .el-col:nth-of-type(1) {
    width: 150px;
  }
}

// 这里的样式在编译之后就不生效了
// 穿刺写法应用在编译之后的盒子类名上
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
